package com.javasearch.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

public class DynamicBeanFileJavaPath {
    private static final Logger log = LoggerFactory.getLogger(DynamicBeanFileJavaPath.class);
    //装载class到jvm内存中,用于之后的class解析,不然有依赖的类会找不到
    public static URLClassLoader preLoadClass( List<String> javaPath) throws Exception {
        for (String s : javaPath) {
            //检查文件是否存在
            File file=new File(s);
            if(!file.exists()){
                throw new Exception(String.format("不存在的路径", s));
            }
        }
        //装载class到jvm内存中
//        URL[] urls = new URL[]{new URL("file:/"+file.getAbsolutePath()+"/")};
        URL[] urls = new URL[javaPath.size()];
        for (int i = 0; i < javaPath.size(); i++) {
            urls[i] = new URL("file:/"+javaPath.get(i)+"/");
        }

        //获取系统的ClassLoader
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); //获取当前线程上下文的ClassLoader
        URLClassLoader loader = new URLClassLoader(urls, contextClassLoader);
        return loader;
    }

    /**
     *  文件版
     * @param fullBeanName  类的全路径名称  : com.obj1.TestB1
     * @param loader  装载的类
     */

    public  static  Class   loadBean(String fullBeanName , URLClassLoader loader) throws Exception {
        Class c = loader.loadClass(fullBeanName);
        return  c;
    }


}
